package com.demo.webapp.ui;

import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.demo.webapp.ui.RepositoryBuilder;
import com.demo.webapp.ui.exception.LoadableResourceException;
/**
 * 持久化对象生成器代理类
 * 对多个组件的持久化生成器进行操作。
 * 
 * @author ryuu.kk
 *
 */
public class RepositoryBuilderDelegate implements RepositoryBuilder {
	
	protected final transient Log log = LogFactory.getLog(super.getClass());

	private Object target;
	private ClassLoader classLoader;
	private List<RepositoryBuilder> builders;
	private ServletContext servletContext;
	
	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	@Override
	public void load() throws LoadableResourceException {
		if (builders == null || builders.size() == 0) {
			log.warn("Repository builder is null.");
			return;
		}
		for (RepositoryBuilder builder : builders) {
			if (log.isDebugEnabled()) {
				log.debug("builder : " + builder.getClass() + " is loading...");
			}
			builder.setBeanClassLoader(classLoader);
			builder.setServletContext(servletContext);
			builder.push(target == null ? new Object() : target);
			builder.load();
			if (log.isDebugEnabled()) {
				log.debug("load seccess.");
			}
		}
	}

	@Override
	public void reload() throws LoadableResourceException {
		load();
	}
	
	public void setRepositoryBuilders(List<RepositoryBuilder> builders) {
		this.builders = builders;
	}

	@Override
	public void push(Object targetObj) {
		this.target = targetObj;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public Object pop() {
		return target;
	}
}